package com.example.securityconfiggen.controller;

import com.example.securityconfiggen.model.PropertiesRequest;
import com.example.securityconfiggen.service.PropertiesService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;

import javax.crypto.BadPaddingException;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.validation.Valid;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import java.util.Map;

@Controller
public class PropertiesController {

    @Autowired
    private PropertiesService propertiesService;

    @GetMapping("/")
    public String index(Model model) {
        model.addAttribute("propertiesRequest", new PropertiesRequest());
        return "index";
    }

    @PostMapping("/process")
    public String processProperties(@Valid @ModelAttribute("propertiesRequest") PropertiesRequest request,
                                   BindingResult bindingResult,
                                   Model model) {
        if (bindingResult.hasErrors()) {
            return "index";
        }

        try {
            // 处理properties内容
            Map<String, String> results = propertiesService.processProperties(request.getProjectName(), request.getPropertiesContent());

            // 将结果放入模型中
            model.addAttribute("md5Result", results.get("md5"));
            model.addAttribute("base64Result", results.get("base64"));
            model.addAttribute("keyvaultCommands", results.get("keyvaultCommands"));
            model.addAttribute("hasResults", true);
            
            // 保持用户输入的内容
            model.addAttribute("propertiesRequest", request);
            
            return "index";
        } catch (Exception e) {
            // 添加错误信息
            bindingResult.rejectValue("propertiesContent", "error.propertiesContent", "处理Properties内容时出错: " + e.getMessage());
            return "index";
        }
    }
} 